package com.ls.atf.trainee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;

public class Trainee {

	public static void main(String args[]) throws MessagingException,
			IOException {
		String login = "eleschynskyy@lvivsoft.com";
		String password = "EfindyourselfL";
		String host = "imap.gmail.com";
		String port = "993";
		String receivedFrom = "registrations@quzetv.com";
		String subject = "Thanks for applying";
		Properties properties = new Properties();
		properties.put("mail.imap.host", host);
		properties.put("mail.imap.port", port);
		properties.setProperty("mail.imap.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.imap.socketFactory.fallback", "false");
		properties.setProperty("mail.imap.socketFactory.port", port);

		Authenticator auth = new MyAuthenticator(login, password);
		Session session = Session.getDefaultInstance(properties, auth);

		Store store = session.getStore("imap");
		store.connect();

		Folder inbox = store.getFolder("INBOX");
		inbox.open(Folder.READ_WRITE);

		Message messages[] = getMessagesFilteredBySenderAndSeen(inbox,
				receivedFrom, subject, true);
		for (int i = 0, n = messages.length; i < n; i++) {
//			System.out.println(i + ": " + messages[i].getFrom()[0] + "\t"
//					+ messages[i].getSubject());
//			String content = messages[i].getContent().toString();
//			System.out.print(content);
//			System.out.println("------------------------------------------------");
			System.out.println(getMessageFullInfo(messages[i]));
		}
		// inbox.setFlags(messages, new Flags(Flags.Flag.DELETED), true);
		inbox.close(false);
		store.close();
	}

	private static Message[] getMessagesFilteredBySenderAndSeen(Folder folder,
			String from, String subject, Boolean seen) {
		Message[] messages = null;
		try {
			SearchTerm filter = new AndTerm(new FromStringTerm(from),
					new SubjectTerm(subject));
			if (!seen) {
				FlagTerm flagSeen = new FlagTerm(new Flags(Flag.SEEN), seen);
				filter = new AndTerm(flagSeen, filter);
			}
			messages = folder.search(filter);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return messages;
	}

	private static String getMessageFullInfo(Message msg) throws IOException,
			MessagingException {
		String from = InternetAddress.toString(msg.getFrom());
		String sBody = null;
		if (from != null) {
			System.out.println("From: " + from);
		}

		String replyTo = InternetAddress.toString(msg.getReplyTo());
		if (replyTo != null) {
			System.out.println("Reply-to: " + replyTo);
		}
		String to = InternetAddress.toString(msg
				.getRecipients(Message.RecipientType.TO));
		if (to != null) {
			System.out.println("To: " + to);
		}
		String subject = msg.getSubject();
		if (subject != null) {
			System.out.println("Subject: " + subject);
		}
		Date sent = msg.getSentDate();
		if (sent != null) {
			System.out.println("Sent: " + sent);
		}
		System.out.println();
		System.out.println("Message: ");

		try {
			Multipart multipart = (Multipart) msg.getContent();
			for (int x = 0; x < multipart.getCount(); x++) {
				BodyPart bodyPart = multipart.getBodyPart(x);
				String sMultiBody = getText(bodyPart);
				sBody = sBody + sMultiBody;
			}
			return sBody;
		} catch (ClassCastException e) {
			sBody = (String) msg.getContent();
			CharSequence searchPhrase = "Ebobe Vombat";
			if (sBody.contains(searchPhrase)) {
				System.out.println("ОК");
            }
			return sBody;
		}
	}

	private static String getText(Part p) throws MessagingException,
	IOException {
		if (p.isMimeType("text/*")) {
			String s = (String) p.getContent();
//			boolean textIsHtml = p.isMimeType("text/html");
			return s;
		}
		if (p.isMimeType("APPLICATION/OCTET-STREAM")) {
			System.out.println("Mail have some attachment : ");
			DataHandler handler = p.getDataHandler();
			return "file name : " + handler.getName();
		}
		if (p.isMimeType("multipart/alternative")) {
			// prefer html text over plain text
			Multipart mp = (Multipart) p.getContent();
			ArrayList<String> strOut = new ArrayList<String>();
			String text = null;
			for (int i = 0; i < mp.getCount(); i++) {
				Part bp = mp.getBodyPart(i);
				if (bp.isMimeType("text/plain")) {
					if (text == null)
						text = getText(bp);
					strOut.add(text);
				} else if (bp.isMimeType("text/html")) {
					String s = getText(bp);
					if (s != null)
						strOut.add(s);
				} else {
					strOut.add(getText(bp));
				}
			}
			return strOut.toString();
		} else if (p.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) p.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				String s = getText(mp.getBodyPart(i));
				if (s != null)
					return s;
			}
		}
		return null;
	}

}
